package com.sgb.jicai.viewmodel;

import androidx.lifecycle.ViewModel;

import com.sgb.jicai.base.JiCaiBaseApi;
import com.sgb.jicai.view.activity.JiCaiSearchActivity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class JiCaiSearchModel extends ViewModel {
    private JiCaiSearchActivity activity;


    //取本地的搜索记录
    public void getSearchHistoryListData() {
        List<String> list = new ArrayList<>();
        //取出本地存的热词
        String historyWords = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.JICAI_SEARCH_HISTORY, "");
        if (null != historyWords && !historyWords.isEmpty()) {
            String[] arr = historyWords.split(","); //字符串转数组,  用,分割
            List<String> resultList = new ArrayList<>(arr.length);
            for (String s : arr) {
                resultList.add(s);
            }
            activity.setSearchHistoryData(resultList);
        } else {
            activity.setSearchHistoryData(list);
        }
    }

    //取服务端的搜索热词
    public void getSearchHotListData() {
        JiCaiBaseApi.getApi().getJiCaiHotWords("10","1").enqueue(new ICallBack<BaseEntity<List<String>>>() {
            @Override
            public void onSuccess(BaseEntity<List<String>> data) {
                DialogHelper.dismissProgressDialog();
                if (data.getData() == null) {
                    return;
                }
                if (data.getState().equals(JiCaiBaseApi.RESPONSE_OK)) {
                    activity.setHotHistoryData(data.getData());
                } else {
                    MToast.showToast(activity, data.getMsg());
                }
            }
        });

    }

    public void search(String keywords) {
        //将搜索词插入平台热词历史
        JiCaiBaseApi.getApi().addJiCaiHotWords(keywords,"1").enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {

            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {

            }
        });
    }


    public void setActivity(JiCaiSearchActivity jiCaiSearchActivity) {
        this.activity = jiCaiSearchActivity;
    }
}
